package com.foreveross.fetl.queue;

import java.util.Calendar;
import java.util.Hashtable;
import java.util.List;

import javax.inject.Inject;

import com.common.remote.ftp.FtpConfig;
import com.common.remote.ftp.FtpTransferException;
import com.common.remote.sftp.SFtpFileTransferClient;
import com.foreveross.fetl.application.ExcelInfoApplication;
import com.foreveross.fetl.common.cfg.system.ReportProperties;
import com.foreveross.fetl.util.DateUtils;
import com.foreveross.fetl.vo.ExcelInfoVO;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class DeleteMetadataProcess {
	
	@Inject
	private ExcelInfoApplication excelInfoApplication;
	
	public void execute(){
		int fileDay =1-Integer.parseInt(null==ReportProperties.getFileDay()? "7" : ReportProperties.getFileDay());
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_MONTH, fileDay);
		deleteData(DateUtils.format(calendar.getTime(), "yyyyMMdd")+"00");
	}

	private void deleteData(String date) {
		List<ExcelInfoVO> listExcelInfo =excelInfoApplication.findByTime(date,null,0);
		String address =ReportProperties.getAddress();
		int port= Integer.parseInt(null==ReportProperties.getPort()? "22":ReportProperties.getPort());
		String userName= ReportProperties.getUserName();
		String passWord =ReportProperties.getPassword();
		String path=ReportProperties.getPath();
		if(!path.endsWith("/")) path+="/";
		FtpConfig config=null;
		SFtpFileTransferClient sftpClient =null;
		boolean flag = false;
		Channel channel = null;
		try {
			config=new FtpConfig(address,port,userName,passWord);
			sftpClient=new SFtpFileTransferClient(config);
			try {
				flag = sftpClient.connect();
			} catch (FtpTransferException e) {
			}
			if(null!=listExcelInfo && listExcelInfo.size()>0){
				for(ExcelInfoVO vo : listExcelInfo){
					if("hangxin".equals(vo.getFileType())){
						continue;
					}
					if (sftpClient.isFileExists(path + vo.getPath())) {
						flag = sftpClient.delete(path + vo.getPath());
						if (flag) {
							excelInfoApplication.delete(vo);
						}
						String[] dirs = (path + vo.getPath()).split("/");
						String dir = findDir(dirs);
						for(int i=0;i<4;i++){
							if(dir.equalsIgnoreCase(path) || dir.endsWith("one-way/") || dir.endsWith("round-trip/")){
								break;
							}
							if (sftpClient.isDirectoryExists(dir)) {
								String[] r = sftpClient.list(dir);
								if (r == null || r.length == 0) {
									JSch jsch = new JSch();
									Session session = jsch.getSession(
											config.getUserName(),
											config.getFtpUrlorIp(),
											config.getFtpPort());
									session.setPassword(config.getPassword());
									Hashtable<String, String> config1 = new Hashtable<String, String>();
									config1.put("StrictHostKeyChecking", "no");
									session.setConfig(config1);
									session.connect();
									channel = session.openChannel("sftp");
									channel.connect();
									ChannelSftp c = (ChannelSftp) channel;
									c.rmdir(dir);
									channel.disconnect();
									dir = findDir(dir.split("/"));
								} else {
									break;
								}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(null!=sftpClient){
				sftpClient.disconnect();
			}
			if (channel != null) {
				channel.disconnect();
			}
		}
			
	}

	private String findDir(String[] dirs) {
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < dirs.length - 1; i++) {
			if (i == dirs.length - 2) {
				buffer.append(dirs[i]);
			} else {
				buffer.append(dirs[i] + "/");
			}

		}
		return buffer.toString();
	}

}
